package com.demo.controller;

import com.demo.utils.Commons;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Controller
@RequestMapping("/upload")
public class UploadController {
    
    @RequestMapping("uploadPic")
    public void upload(HttpServletRequest request, String fileName, PrintWriter out){
        //把request强转成MultipartHttpServletRequest对象
        MultipartHttpServletRequest mh= (MultipartHttpServletRequest) request;
        //根据文件名获取文件对象
        CommonsMultipartFile cm= (CommonsMultipartFile) mh.getFile(fileName);
        byte[] fbytes = cm.getBytes();
        
        //文件名在服务器中可能存在？
        String newFile="";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyymmddHHmmss");
        newFile = sdf.format(new Date());
    
        Random r = new Random();
        for (int i = 0; i <3; i++) {
            newFile=newFile+r.nextInt(10);
        }
        
        //获取文件的扩展名
        String originalFilename = cm.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        
        //创建jersey服务器
        Client client=Client.create();
        //把文件关联到远程服务器
        WebResource resource = client.resource(Commons.PIC_HOST + "/upload/" + newFile + suffix);
        //上传
        resource.put(String.class,fbytes);
        
        //ajax回调函数
        //图片回显：需要图片完整路径
        //数据库保存图片的相对路径
        String fullPath=Commons.PIC_HOST + "/upload/" + newFile + suffix;
        
        String relativePath="/upload/" + newFile + suffix;
        
        String result="{\"fullPath\":\""+fullPath+"\",\"relativePath\":\""+relativePath+"\"}";
        
        out.write(result);
    }
}
